<template>
    <div class="map_content">
        <el-amap :center="position" :zoom="zoom" @click="clickMap">
            <el-amap-search-box @select="movePoi" @choose="movePoi" datatype="poi" />
            <el-amap-marker :visible="markerVisible" :position="position" @click="clickMarker" />
        </el-amap>
    </div>
</template>

<script setup>
import { ref, defineEmits, defineProps, watch } from "vue"
import $ from "@util/base"
import box from "@ui/messageBox";
const emit = defineEmits(['select'])
const zoom = ref(18)
const markerVisible = ref(true)
const defaultPosition = [121.499718, 31.239703]

const props = defineProps({
    disabled: {
        type: Boolean,
        default: false
    },
    position: {
        type: Array
    }
})

const position = ref(defaultPosition)
watch(() => props.position, val => {
    if (val[0] != null && val[1] != null) {
        position.value = val
    }
})

function clickMarker() {
    if (!props.disabled) {
        box.open("确认选择", curPOI.address || '', () => {
            emit('select', curPOI)
        })
    }
}

function clickMap(evt) {
    if (!props.disabled) {
        curPOI = {
            lng: evt.lnglat.lng,
            lat: evt.lnglat.lat,
            address: null,
        }
        position.value = [evt.lnglat.lng, evt.lnglat.lat]

        // eslint-disable-next-line no-undef
        let geocoder = new AMap.Geocoder({ city: '全国' })
        geocoder.getAddress(position.value, (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
                console.log(result)
                curPOI.address = result.regeocode.formattedAddress
            }
        })
    }
}

var curPOI = null
function movePoi(data) {
    if ($.isNotEmpty(data.poi.location)) {
        markerVisible.value = true
        position.value = [data.poi.location.lng, data.poi.location.lat]
        curPOI = {
            lng: data.poi.location.lng,
            lat: data.poi.location.lat,
            address: data.poi.district + data.poi.address,
        }
    }
}

</script>
<style>
.map_content {
    width: 700px;
    height: 400px;
}
</style>